package com.corn.turorial.spring.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function : 自定义异常解析器
 * @since : 2021/2/7 14:48
 */
@Slf4j
public class MyCustomerHandlerExceptionResolver implements HandlerExceptionResolver, Ordered {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        if (ex instanceof MyRuntimeException) {
            log.error("出现了异常! ", ex);
            try {
                response.getWriter().write(ex.getMessage() + " [MyCustomerHandlerExceptionResolver!]");
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 可以自定义往哪里跳 一旦返回了mav 之后 就确定用这个HandlerExceptionResolver 处理
            ModelAndView mav = new ModelAndView();
            return mav;
        }
        return null;
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
